//
//  DTMultiLanguage.m
//  
//
//  Created by JianWei Chen on 16/7/8.
//  Copyright © 2016年 JianWei Chen. All rights reserved.
//

#import "DTMultiLanguage.h"
#import <objc/runtime.h>

/**
 *  UILabel for 多语言
 */

@interface TEALocalizableTool ()

#define LanguageList @[@"en",@"de",@"fr",@"it",@"nl",@"cs-CZ",@"pl-PL",@"da",@"sv-AX",@"nb",@"fi",@"is",@"lv",@"es",@"zh-Hans"]
#define LanguageRangeList @[@"en",@"de",@"fr",@"it",@"nl",@"cs",@"pl",@"da",@"sv",@"nb",@"fi",@"is",@"lv",@"es",@"zh"]

@property (nonatomic, strong) NSBundle *currentBundle;

@end

@implementation TEALocalizableTool

+ (instancetype)shareInstance {
    static TEALocalizableTool *localizableTool = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        localizableTool = [[TEALocalizableTool alloc] init];
    });
    return localizableTool;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initLanguage];
    }
    return self;
}

- (void)initLanguage {
    NSString *saveLan = [[[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"] firstObject];;
    if (YES) {
        saveLan = [[[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"] firstObject];
        if ([saveLan isEqualToString:@"zh-Hans"]||[saveLan isEqualToString:@"zh-Hans-CN"]) {
        
        }else{
            
            saveLan = @"en";
        }
        
        
        BOOL isSearch = NO;
        for (int i = 0; i < 15; i++) {
            NSString *string = LanguageRangeList[i];
            if ([saveLan rangeOfString:string].location != NSNotFound) {
                saveLan = LanguageList[i];
                isSearch = YES;
                break;
            }
        }
    }
    NSString *path = [[NSBundle mainBundle] pathForResource:saveLan ofType:@"lproj"];
    NSBundle *bundle = [NSBundle bundleWithPath:path];
    if (bundle) {
        _currentLanguage = saveLan;
        _currentBundle = bundle;
    }
    [[NSUserDefaults standardUserDefaults] setObject:_currentLanguage forKey:UserLanguage];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

@synthesize currentLanguage = _currentLanguage;
- (void)setCurrentLanguage:(NSString *)currentLanguage {
    [[NSNotificationCenter defaultCenter]postNotificationName:@"NotifyLanguageChange" object:nil];
    
    if (_currentLanguage == currentLanguage) {
        return;
    }
    
    NSString *path = [[NSBundle mainBundle] pathForResource:currentLanguage ofType:@"lproj"];
    NSBundle *bundle = [NSBundle bundleWithPath:path];
    if (bundle) {
        _currentLanguage = currentLanguage;
        _currentBundle = bundle;
    }
    [[NSUserDefaults standardUserDefaults] setObject:_currentLanguage forKey:UserLanguage];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSString *)currentLanguage {
    return _currentLanguage;
}

- (NSString *)localizedStringForKey:(NSString *)key {
    NSString *value = [_currentBundle localizedStringForKey:key value:nil table:nil];
    if (value) {
        return value;
    }else {
        return key;
    }
}

@end

@implementation UIView (FonSelf)

static char strAddrKey = 'a';

- (NSString *)fontSelfKey
{
    return objc_getAssociatedObject(self, &strAddrKey);
}
- (void)setFontSelfKey:(NSString *)fontSelfKey
{
    objc_setAssociatedObject(self, &strAddrKey, fontSelfKey, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

@end


@implementation UILabel (FontSelf)

+ (void)load
{
    Class class = [self class];
    
    SEL originalSelector = @selector(awakeFromNib);
    SEL swizzledSelector = @selector(my_awakeFromNib);
    
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    
    BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
    if (success) {
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

- (void)my_awakeFromNib
{
    self.fontSelfKey = self.text;
    
    [self textChangeContent];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textChangeContent) name:@"NotifyLanguageChange" object:nil];
}

- (void)textChangeContent
{
    //设置字体
    if ([self.font.fontName rangeOfString:@"Bold"].location != NSNotFound){
        LabelFontBold(self);
    }else{
        LabelFontRegular(self);
    }
    
    //设置多语言
    if (self.text.length != 0) {
        self.text = MyNSLocalizedString(self.fontSelfKey);
    }
}

@end


/**
 *  UIButton for 多语言
 */

@implementation UIButton (FontSelf)

+ (void)load
{
    Class class = [self class];
    
    SEL originalSelector = @selector(awakeFromNib);
    SEL swizzledSelector = @selector(my_awakeFromNib);
    
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    
    BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
    if (success) {
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

- (void)my_awakeFromNib
{
    
    self.fontSelfKey = self.titleLabel.text;
    
    [self textChangeContent];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textChangeContent) name:@"NotifyLanguageChange" object:nil];
}

- (void)textChangeContent
{
    //设置字体
    if ([self.titleLabel.font.fontName rangeOfString:@"Bold"].location != NSNotFound){
        LabelFontBold(self.titleLabel);
    }else{
        LabelFontRegular(self.titleLabel);
    }
    //设置多语言
    if (self.titleLabel.text.length != 0) {
        [self setTitle:MyNSLocalizedString(self.fontSelfKey) forState:UIControlStateNormal];
    }
}
@end

/**
 *  UITextView for 多语言
 */

@implementation UITextView (FontSelf)

+ (void)load
{
    Class class = [self class];
    
    SEL originalSelector = @selector(awakeFromNib);
    SEL swizzledSelector = @selector(my_awakeFromNib);
    
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    
    BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
    if (success) {
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

- (void)my_awakeFromNib
{
    
    self.fontSelfKey = self.text;
    
    [self textChangeContent];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textChangeContent) name:@"NotifyLanguageChange" object:nil];
}

- (void)textChangeContent
{
    //设置字体
    if ([self.font.fontName rangeOfString:@"Bold"].location != NSNotFound){
        LabelFontBold(self);
    }else{
        LabelFontRegular(self);
    }
    
    //设置多语言
    if (self.text.length != 0) {
        self.text = MyNSLocalizedString(self.fontSelfKey);
    }
}
@end

/**
 *  UITextView for 多语言
 */

@implementation UITextField (FontSelf)

+ (void)load
{
    Class class = [self class];
    
    SEL originalSelector = @selector(awakeFromNib);
    SEL swizzledSelector = @selector(my_awakeFromNib);
    
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    
    BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
    if (success) {
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

- (void)my_awakeFromNib
{
    
    self.fontSelfKey = self.placeholder;
    
    [self textChangeContent];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textChangeContent) name:@"NotifyLanguageChange" object:nil];
}

- (void)textChangeContent
{
    //设置字体
    if ([self.font.fontName rangeOfString:@"Bold"].location != NSNotFound){
        LabelFontBold(self);
    }else{
        LabelFontRegular(self);
    }
    
    //设置多语言
    if (self.text.length != 0) {
        self.text = MyNSLocalizedString(self.text);
    }
    if (self.placeholder.length != 0) {
        self.placeholder = MyNSLocalizedString(self.fontSelfKey);
    }
}
@end

